package cn.xianshu.mq.consumer;



import cn.xianshu.to.EmailTo;
import cn.xianshu.to.MessageTo;
import cn.xianshu.to.SMSTo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.List;
import static cn.xianshu.constants.RabbitMQConstans.*;

@Component
@Slf4j
public class CourseConsumer {
    //消费短信：从队列中获取短信消息
    //1.拿到手机号和内容
    //2.发送短信：中国网建 x1111,111,111
    //3.保存发送记录到数据库
    //4.手动签收
    @RabbitListener(queues = QUEUE_NAME_OF_SMS ,containerFactory = "rabbitListenerContainerFactory")
    public void consumerSMS(@Payload SMSTo smsTo, Channel channel, Message message){
        // 1.拿到手机号和内容
        List<String> phones = smsTo.getPhones();
        // 2.发送短信：中国网建 1111,111,111
        String phoneStrs = StringUtils.join(phones, ",");
        log.info("批量发送短信，号码:{} - 内容：{}",phoneStrs ,smsTo.getContent());
        // 3.保存发送记录到数据库
        // 省略..TODO
        // 4.签收消息
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //邮件
    @RabbitListener(queues = QUEUE_NAME_OF_EMAIL,containerFactory = "rabbitListenerContainerFactory")
    public void consumerEmail(@Payload EmailTo emailTo, Channel channel, Message message){
        //1.拿到邮箱
        emailTo.getEmails().forEach(email->{
            //2.发送邮件
            log.info("发送邮件，邮箱：{} - 标题：{} - 内容：{}",email ,emailTo.getTitle(),emailTo.getContent() );
            //3.保存邮件发送记录到数据库 TODO
        });
        //4.签收消息
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //站内信
    @RabbitListener(queues = QUEUE_NAME_OF_MESSAGE,containerFactory = "rabbitListenerContainerFactory")
    public void consumerMessage(@Payload MessageTo messageTo, Channel channel, Message message){
        //1.拿到用户ID
        messageTo.getUserIds().forEach(userId->{
            //2.保存站内信//TODO
            log.info("保存站内信，用户ID：{} - 标题：{} - 内容：{}",userId ,messageTo.getTitle(),messageTo.getContent() );
        });
        //3.签收消息
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
